package com.game.id;

import com.dats.db.NameKeyUnit;
import com.dats.db.NameMap;
import com.dats.entity.CacheBean;
import com.game.dao.DatSDao;
import com.nets.pool.ServerPool;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author sig
 * @since 2016/9/26
 */
public class IdMg implements com.dats.i.IdI, IdI {
    private static Map<Class<?>, AtomicLong> idMap = new
            ConcurrentHashMap<>();

    @Override
    public <T extends CacheBean> void putMaxId(Class<T> clazz) {
        NameKeyUnit unit = NameMap.getNameKeyUnit(clazz);

        if (null == unit) return;
        int end = String.valueOf(ServerPool.serverId).length() + 1;
        String sql = "SELECT MAX(CONVERT(SUBSTR(`" + unit.getSaveKey() +
                "`," + end + "),UNSIGNED)) FROM `" + unit.getTableName() + "`";
        AtomicLong maxId = new AtomicLong(DatSDao.loadLong(sql));
        idMap.put(clazz, maxId);
    }

    @Override
    public <T extends CacheBean> long newId(T t) {
        AtomicLong maxId = idMap.get(t.getClass());

        if (null == maxId)
            throw new RuntimeException(t.getClass().getSimpleName() +
                    " is not configured in NameKey.");
        return getId(maxId.incrementAndGet());
    }

    @Override
    public <T extends CacheBean> long newId(Class<T> clazz) {
        AtomicLong maxId = idMap.get(clazz);

        if (null == maxId)
            throw new RuntimeException(clazz.getSimpleName() +
                    " is not configured in NameKey.");
        return getId(maxId.incrementAndGet());
    }

    private long getId(long l) {
        return Long.parseLong(String.valueOf(ServerPool.serverId) + l);
    }
}
